const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { ensureDirExists, generateRandomFilename } = require('./helpers');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
ensureDirExists(uploadDir);
ensureDirExists(path.join(uploadDir, 'videos'));
ensureDirExists(path.join(uploadDir, 'covers'));
ensureDirExists(path.join(uploadDir, 'temp'));
ensureDirExists(path.join(uploadDir, 'chunks'));

// 视频文件存储配置
const videoStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const videoDir = path.join(uploadDir, 'videos');
    ensureDirExists(videoDir);
    cb(null, videoDir);
  },
  filename: function (req, file, cb) {
    const filename = generateRandomFilename(file.originalname);
    cb(null, filename);
  }
});

// 封面图片存储配置
const coverStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const coverDir = path.join(uploadDir, 'covers');
    ensureDirExists(coverDir);
    cb(null, coverDir);
  },
  filename: function (req, file, cb) {
    const filename = generateRandomFilename(file.originalname);
    cb(null, filename);
  }
});

// 视频文件过滤器
const videoFileFilter = (req, file, cb) => {
  // 接受的视频格式
  const allowedTypes = /mp4|avi|mov|wmv|flv|webm/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);
  
  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('只支持 mp4/avi/mov/wmv/flv/webm 格式的视频文件'));
  }
};

// 封面图片过滤器
const coverFileFilter = (req, file, cb) => {
  // 接受的图片格式
  const allowedTypes = /jpeg|jpg|png|gif/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);
  
  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb(new Error('只支持 jpg/png/gif 格式的图片文件'));
  }
};

// 创建上传中间件
const videoUpload = multer({ 
  storage: videoStorage,
  fileFilter: videoFileFilter,
  limits: {
    fileSize: 2 * 1024 * 1024 * 1024 // 2GB
  }
});

const coverUpload = multer({ 
  storage: coverStorage,
  fileFilter: coverFileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 生成访问URL
const generateFileUrl = (filepath, req) => {
  // 在实际部署时，这里应该返回完整的URL
  // 例如: https://yourdomain.com/uploads/videos/filename.mp4
  const relativePath = path.relative(uploadDir, filepath).replace(/\\/g, '/');
  return `${req.protocol}://${req.get('host')}/uploads/${relativePath}`;
};

module.exports = {
  videoUpload,
  coverUpload,
  generateFileUrl
};